package com.stlm2.dems.service;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.*;
import com.stlm2.dems.entity.*;
import com.stlm2.util.Convert;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("entranceService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class EntranceService extends BaseServiceImpl<Entrance> {

	@Resource
	private EntranceDao entranceDao;
	@Resource
	private UserService userService;
	@Resource
	private UserDao userDao;
	@Resource
	private SeckillGoodsDao seckillGoodsDao;
	@Resource
	private ActivityService activityService;
	@Resource
	private DdmGoodsDao ddmGoodsDao;
	@Resource
	private GoodSpecificationDao goodSpecificationDao;
	@Override
	protected BaseDao <Entrance> getDao() {
		return entranceDao;
	}

	public List<ModelMap> convert(List<Entrance> entrances ) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (entrances != null && entrances.size() > 0) {
			for (Entrance entrance : entrances) {
				ModelMap map = buildModel(entrance);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModel(Entrance entrance) {

		ModelMap model = new ModelMap();
		model.put("id",entrance.getId());
		model.put("name",entrance.getName());
		model.put("shortName", entrance.getShortName()!=null?entrance.getShortName():"");
		model.put("img",entrance.getImg());
		model.put("url",entrance.getUrl());
		model.put("typeValue",entrance.getTypeValue());
		model.put("type",entrance.getType().toString());
		model.put("state",entrance.getState()==1?"有效":"无效");
		model.put("appUrl",entrance.getAppUrl());

//		model.put("createTime", Convert.toFullYMDHMS(entrance.getCreateTime()));
//		model.put("createUserName",userService.getById(entrance.getCreateUserId()).getRealName());

		return model;
	}

	public List<ModelMap> convert_index(List<Entrance> entrances ,String companyCode) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (entrances != null && entrances.size() > 0) {
			for (Entrance entrance : entrances) {
				ModelMap map = buildModel_index(entrance,companyCode);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModel_index(Entrance entrance,String companyCode) {

		ModelMap model = new ModelMap();
		model.put("id",entrance.getId());
		model.put("name",entrance.getName());
		model.put("shortName", entrance.getShortName()!=null?entrance.getShortName():"");
		String mainImg=entrance.getImg();
		model.put("url",entrance.getUrl());
		model.put("typeValue",entrance.getTypeValue());
		model.put("type",entrance.getType().toString());
		model.put("state",entrance.getState()==1?"有效":"无效");
		model.put("appUrl",entrance.getAppUrl());
		if(entrance.getAppUrl().equals("seckillGoods")){
			model.put("appUrl","");
			int pageNo=1;
			Date current = new Date();
			Calendar cal=Calendar.getInstance();
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH) + 1;
			int day = cal.get(Calendar.DAY_OF_MONTH);

			String t=" 23:59:59";
			String t2 = Convert.toShortYMD(current)+t;
			Date timeEnd=null;
			try {
				timeEnd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(t2);
			} catch (Exception e) {
				System.out.println("无法解析时间k2" + t2);
			}
			SeckillGoods param=new SeckillGoods();
			param.setYear(year);
			param.setMonth(month);
			param.setDay(day);
			param.setGoodsState(true);
			PageView pageview=seckillGoodsDao.queryPageView(pageNo,3,param);
			model.put("timeNow",current.getTime());
			model.put("endTime",timeEnd.getTime());
			model.put("seckillState",activityService.SeckillActivityState(companyCode));
			if (pageview != null&&pageview.getRecords().size()>0){
				List<SeckillGoods> list=pageview.getRecords();
				SeckillGoods seckillGoods=list.get(0);
				DdmGoods goods=ddmGoodsDao.getById(seckillGoods.getGoodsId());
				if(goods!=null){
					mainImg=goods.getMainImg().split(",")[0];
				}
				if(seckillGoods.getGoodsSpecificationId()!=null){
					GoodSpecification specification=goodSpecificationDao.getById(seckillGoods.getGoodsSpecificationId());
					if(specification!=null){
						mainImg=specification.getImage();
					}
				}

			}
            if(activityService.SeckillActivityState(companyCode)){
				model.put("state","有效");
			}else {
				model.put("state","无效");
			}
			model.put("typeValue",3);
			model.put("type",EntranceType.Type3.toString());
		}
		model.put("img",mainImg);
		return model;
	}
	public String getDetails(ModelMap model,String token,String id){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (!NumberUtils.isDigits(id)) {
			return CodeContent.getModelByCode(0, "id不能为空", model);
		}
		Entrance entrance=entranceDao.getById(Integer.parseInt(id));
		if(entrance==null){
			return CodeContent.getModelByCode(0, "记录不存在", model);
		}
		return CodeContent.getModelByCode(1, "", buildModel(entrance));

	}
	/*
    *后台调用
    * zlq
     */
	public String searchEntrance(String token,ModelMap model, String page,String typeValue){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if (!NumberUtils.isDigits(typeValue)) {
			return CodeContent.getModelByCode(0, "类型不能为空", model);
		}
		if(EntranceType.getByIntValue(Integer.parseInt(typeValue))==null){
			return CodeContent.getModelByCode(0, "类型不存在", model);
		}
		Entrance entrance=new Entrance();
		entrance.setTypeValue(Integer.parseInt(typeValue));
		pageview=entranceDao.queryPageView(pageNo,pageSize,entrance);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convert(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}

		return new JSONObject(model).toString();
	}

/*
*前台调用
* zlq
 */
	public String getEntrance(ModelMap model,Boolean state,String companyCode){
		Entrance entrance=new Entrance();
		entrance.setState(state?1:0);
		entrance.setType(EntranceType.Type1);
		List <Entrance> entranceList1=entranceDao.queryPageView(-1,-1,entrance).getRecords();
		entrance.setType(EntranceType.Type2);
		List <Entrance> entranceList2=entranceDao.queryPageView(-1,-1,entrance).getRecords();
		Map<String,Object> datas = new HashMap<String, Object>();
		datas.put("entrance1",convert_index(entranceList1,companyCode));
		datas.put("entrance2",convert_index(entranceList2,companyCode));
		model.put("code",1);
		model.put("msg","success");
		model.put("datas",datas);

		return  new JSONObject(model).toString();
	}


	public String updateEntrance(ModelMap model,String token,String id,String name,String shortName,String appUrl,String img,String url,boolean state) {
		User user = userService.getByToken(token);
		if (user == null)
			return CodeContent.returnLogin();
		if(!NumberUtils.isDigits(id)){
			return CodeContent.getModelByCode(0, "ID参数错误", model);
		}
		if (StringUtils.isEmpty(name)) {
			return CodeContent.getModelByCode(0, "标题名不能为空", model);
		}
		if (StringUtils.isEmpty(img)) {
			return CodeContent.getModelByCode(0, "图片不能为空", model);
		}
		Entrance entrance=entranceDao.getById(Integer.parseInt(id));
		if(entrance==null){
			return CodeContent.getModelByCode(0, "ID不存在", model);
		}
		if(state){
			Entrance entrance2=new Entrance();
			entrance2.setState(1);
			entrance2.setType(entrance.getType());
			List<Entrance> entranceList=entranceDao.queryPageView(-1,-1,entrance2).getRecords();
			int size=entranceList.size();
			for(Entrance entrance3:entranceList){
				if(entrance3.getId()==entrance.getId()){
					size=size-1;
				}
			}
			if(size>1){
				return CodeContent.getModelByCode(0, "最多只能有2个有效的设置", model);
			}
		}
		entrance.setName(name);
		entrance.setShortName(shortName);
		entrance.setAppUrl(appUrl);
		entrance.setImg(img);
		entrance.setUrl(url);
		entrance.setState(state?1:0);
		entranceDao.modify(entrance);
		return CodeContent.getModelByCode(1, "", model);
	}
}